package com.itheima.reggie.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.ExcelOrderDto;
import com.itheima.reggie.dto.OrderDto;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.log.MyLog;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrdersService;
import com.itheima.reggie.service.ShoppingCartService;
import com.itheima.reggie.utils.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrdersService orderService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    /**
     * 用户下单
     * @param orders
     * @return
     */
    @PostMapping("/submit")

    public R<String> submit(@RequestBody Orders orders){
        log.info("订单数据：{}",orders);
        orderService.submit(orders);
        return R.success("下单成功");
    }

    /**
     * 修改订单派送状态
     * @param orders
     * @return
     */
    @PutMapping

    public R<String> list(@RequestBody Orders orders){
        LambdaUpdateWrapper<Orders> lqw =new LambdaUpdateWrapper<>();
        lqw.eq(Orders::getUserId, orders.getUserId());
        lqw.eq(Orders::getId, orders.getId());
        lqw.set(Orders::getStatus,orders.getStatus());
        orderService.updateById(orders);
        return  R.success("派送成功");
    }

    /**
     * 移动端订单
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page<OrderDto>> getPage(Integer page, Integer pageSize){
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Orders::getUserId, BaseContext.getCurrentId());
        lqw.orderByDesc(Orders::getCheckoutTime);
        orderService.page(ordersPage, lqw);

        Page<OrderDto> orderDtoPage = new Page<>();
        BeanUtils.copyProperties(ordersPage,orderDtoPage,"records");
        List<Orders> records = ordersPage.getRecords();
        List<OrderDto> orderDtoList = new ArrayList<>();
        orderDtoList = records.stream().map(record -> {
            OrderDto orderDto = new OrderDto();
            BeanUtils.copyProperties(record,orderDto);
            LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(OrderDetail::getOrderId, orderDto.getId());
            List<OrderDetail> orderDetails = orderDetailService.list(wrapper);
            orderDto.setOrderDetails(orderDetails);
            return orderDto;

        }).collect(Collectors.toList());
        orderDtoPage.setRecords(orderDtoList);
        return R.success(orderDtoPage);
    }

    /**
     * 订单明细分页查询
     * @param page
     * @param pageSize
     * @param beginTime
     * @param endTime
     * @param number
     * @return
     */
    @GetMapping("/page")
    public R<Page<Orders>> findPage(Integer page , Integer pageSize, @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date beginTime, @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endTime, String number){
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.eq(StringUtils.isNotEmpty(number),Orders::getNumber,number);
        lqw.between(beginTime != null,Orders::getCheckoutTime,beginTime,endTime);
        lqw.between(endTime != null,Orders::getCheckoutTime,beginTime,endTime);
        orderService.page(ordersPage,lqw);
        return R.success(ordersPage);
    }

    /**
     * 再来一单
     * @param orders
     * @return
     */
    @PostMapping("/again")
    public R<String> again(@RequestBody Orders orders) {
        LambdaQueryWrapper<OrderDetail> lqw = new LambdaQueryWrapper<>();
        lqw.eq(OrderDetail::getOrderId,orders.getId());
        //获取订单id所关联的订单明细表
        List<OrderDetail> orderDetailList = orderDetailService.list(lqw);
        List<ShoppingCart> shoppingCartList = new ArrayList<>();
        shoppingCartList = orderDetailList.stream().map(detail -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(detail,shoppingCart);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            return shoppingCart;
        }).collect(Collectors.toList());
        //清空购物车
        LambdaQueryWrapper<ShoppingCart> query = new LambdaQueryWrapper<>();
        query.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
        shoppingCartService.remove(query);
        //批量保存到购物车
        shoppingCartService.saveBatch(shoppingCartList);
        return  R.success("再来一单");
    }

    /**
     * 导出Excel
     * @param response
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) {
        try {
            //设置下载请求头
            ExcelUtils.setDownLoadHeader("订单.xlsx",response);
            //获取需要导出的数据
            List<Orders> list = orderService.list();
            ArrayList<ExcelOrderDto> orders = new ArrayList<>();
            //Bean拷贝
            for (Orders orders1 : list) {
                ExcelOrderDto ordersDto = new ExcelOrderDto();
                BeanUtils.copyProperties(orders1,ordersDto);
                //long类型的id在excel中会自动变成科学计数法的形式，所以要改成String类型的数据。
                ordersDto.setId(orders1.getId().toString());
                ordersDto.setUserId(orders1.getUserId().toString());
                if(orders1.getPayMethod()==1){
                    ordersDto.setPayMethod("微信");
                }else if(orders1.getPayMethod()==2){
                    ordersDto.setPayMethod("支付宝");
                }
                orders.add(ordersDto);
            }
            //把数据写入excel中
            EasyExcel.write(response.getOutputStream(), ExcelOrderDto.class)
                    .autoCloseStream(Boolean.FALSE).sheet("订单导出")
                    .doWrite(orders);
        } catch (Exception e) {
            e.printStackTrace();
            //出现异常
            R result = R.error(e.toString());
        }
    }
}